package com.ruoyi.common.utils;

import com.ruoyi.common.core.mail.Mail;
import org.apache.commons.lang3.ObjectUtils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

/**
 * @author :chenzengzhi
 * @date :2023/12/4 16:07
 * @logo :#^_^#
 */
public class SendEmailUtils {
    public static Session createSession(String host, String userName, String passWord) {
        Properties prop = new Properties();
        prop.setProperty("mail.host", host);
        prop.setProperty("mail.smtp.auth", "true");
        prop.setProperty("mail.smtp.ssl.enable", "true");
        // 创建验证器
        Authenticator auth = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, passWord);
            }
        };
        // 获取session对象
        return Session.getInstance(prop, auth);
    }

    /**
     * 发送指定的邮件
     *
     * @param mail
     */
    public static void send(Session session, Mail mail) throws Exception {

        MimeMessage msg = new MimeMessage(session);
        // 设置发件人
        msg.setFrom(new InternetAddress(mail.getSendFrom()));
        // 设置收件人
        msg.addRecipients(Message.RecipientType.TO, mail.getSendTo());
        //设置抄送
        if (!ObjectUtils.isEmpty(mail.getSendCopy())) {
            msg.addRecipients(Message.RecipientType.CC, mail.getSendCopy());
        }
        //设置主题
        msg.setSubject(mail.getSubject());
        //创建部件集对象
        MimeMultipart parts = new MimeMultipart();
        //创建一个部件
        MimeBodyPart part = new MimeBodyPart();
        //设置邮件文本内容
        part.setContent(mail.getContent(), "text/html;charset=utf-8");
        //把部件添加到部件集中
        parts.addBodyPart(part);
        //给邮件设置内容
        msg.setContent(parts);
        //发邮件
        Transport.send(msg);
    }
}
